﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// “基本页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234237 上有介绍

namespace DianDian
{
    /// <summary>
    /// 基本页，提供大多数应用程序通用的特性。
    /// </summary>
    public sealed partial class MainPage : DianDian.Common.LayoutAwarePage
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
        WebView web = new WebView();
        string clientid = "5V3fxt7fex";
        string clietnSecret = "EmBXlTu6yZVvLqr3RghIXZigHGBerZgh00HN";
        string redirectUrl = "http://www.baidu.com";
        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="navigationParameter">最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的参数值。
        /// </param>
        /// <param name="pageState">此页在以前会话期间保留的状态
        /// 字典。首次访问页面时为 null。</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            DianDian.API.DefaultClient client = new API.DefaultClient();
            var aa = await client.Execute(new API.Request.UserHomeRequest() { Type = "text" });
            foreach (var item in aa.Response.Posts)
            {
                item.RowSpan = item.ColSpan = 1;
                item.Tag = 1;
            }
      
            gridview.ItemsSource = aa.Response.Posts;
            //var stream = await App.Current.GetApplicationStream("html.txt");
            ////var file=stream.
            //var txt = await Windows.Storage.FileIO.ReadTextAsync(stream);
            //web.NavigateToString(txt);
            //web.ScriptNotify += web_ScriptNotify;



            //var stream = await App.Current.GetApplicationStream("02_1769902385_3641757.mp3");
            //media.SetSource(await stream.OpenAsync(Windows.Storage.FileAccessMode.Read), "audio/x-ms-mp3");

            //media.Source = new Uri("http://f3.xiami.net/4/180/78980/414285/02_1769902385_3641757.mp3");

            ////http://www.xiami.com/song/374190

            //  //var r=   System.Net.HttpWebRequest.CreateHttp("http://www.xiami.com/song/374190");
            //  //r.Headers[System.Net.HttpRequestHeader.UserAgent] = "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3";
            //  //var res = await r.GetResponseAsync();
            //  //System.IO.StreamReader reader = new StreamReader(res.GetResponseStream());
            //  //string str = reader.ReadToEnd();
            //HTTP h = new HTTP("http://www.xiami.com/song/374190");
            //var aa = await h.RequestAsync();
        }

        void web_ScriptNotify(object sender, NotifyEventArgs e)
        {

        }

        /// <summary>
        /// 保留与此页关联的状态，以防挂起应用程序或
        /// 从导航缓存中放弃此页。值必须符合
        /// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
        /// </summary>
        /// <param name="pageState">要使用可序列化状态填充的空字典。</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Button b = sender as Button;
            API.Domain.Post p = b.DataContext as API.Domain.Post;
            var str = await Utils.MusicUrlManage.GetMusicUrl(p);
            //System.Net.Http.HttpClient http = new System.Net.Http.HttpClient();
            //var stream = await http.GetByteArrayAsync(str);
            //StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            //var storageFile = await storageFolder.CreateFileAsync("aaaa.mp3", CreationCollisionOption.ReplaceExisting);
            //await FileIO.WriteBytesAsync(storageFile, stream);
            //media.SetSource(await Windows.Storage.Streams.RandomAccessStreamReference.CreateFromUri(new Uri(str)).OpenReadAsync(), "audio/x-ms-mp3");

            //media.AudioCategory = AudioCategory.ForegroundOnlyMedia;
            //media.Source = new Uri(str);
            //media.Play();
        }

        private async void Button_Click_2(object sender, RoutedEventArgs e)
        {
            //var stream = await App.Current.GetApplicationStream("script.txt");
            ////var file=stream.
            //var txt = await Windows.Storage.FileIO.ReadTextAsync(stream);
            web.InvokeScript("eval", new string[] { "function documentMouseDown(str){window.external.notify(sospa(str));}" });
            web.InvokeScript("documentMouseDown", new string[] { "4h%2Fxit6F%82.t3Ffi.%22248mtA%3an2%4F54pp%2.meF242_53" });
        }

        private void media_MediaOpened_1(object sender, RoutedEventArgs e)
        {

        }

        private void media_MediaFailed_1(object sender, ExceptionRoutedEventArgs e)
        {

        }

        private void gridview_ItemClick(object sender, ItemClickEventArgs e)
        {
            G.Controls.FlyoutPopup f = new G.Controls.FlyoutPopup() { Width = 480 };
            API.Domain.Post p = e.ClickedItem as API.Domain.Post;
            WebView w = new WebView();
            w.NavigateToString(p.Body);
            f.Content = w;
            f.IsOpen = true;

            //this.Frame.Navigate(typeof(View.PostDetailPage), e.ClickedItem);
        }
    }

    public class HTTP : G.Net.HttpRequest
    {
        public HTTP(string str)
            : base(str)
        {
            base.Method = G.Net.HttpMethod.Get;
        }
        protected override void AppendHeaders(System.Net.Http.Headers.HttpRequestHeaders headers)
        {
            base.AppendHeaders(headers);
            //Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3
            //headers.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("Mozilla", "5.0"));
            //headers.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue(


        }
    }
}
